import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * @param {function} fetch 拉取列表的 api 方法
 * @param {Object} params condition 查询条件
 * @param {Object} params  page 分页信息
 * @param {Object} params fn 自定义处理单项数据函数
 */
export function useListLoader(fetch, condition, page, fn) {
    const defaultCondition = { ...condition }
    const searchForm = reactive(condition)
    const pageForm = reactive(page)
    const tableData = ref([])
    const currentPage = ref(1)
    const total = ref(0)
    const loading = ref(false)
    fn = fn || ((o) => o)
    
    const queryList = async () => {
        try {
            loading.value = true
            let res = await fetch({
                ...pageForm,
                param: { ...searchForm }
            })
            total.value = res.total
            tableData.value = res.data.map(item => {
                return fn(item)
            })
        } catch(e) {
            ElMessage.error(`${e}`)
        } finally {
            loading.value = false
        }
    }
    
    const resetList = () => {
        total.value = 0
        currentPage.value = 1
        tableData.value = []
    }

    const search = () => {
        resetList()
        queryList()
    }
    
    const resetSearch = () => {
        Object.keys(searchForm).forEach(k => {
            searchForm[k] = defaultCondition[k]
        })
    }
    
    const handleSizeChange = (val) => {
        pageForm.pageSize = Number(val)
        resetList()
        queryList()
    }
    
    const handleCurrentChange = (val) => {
        pageForm.pageNum = Number(val)
        resetList()
        queryList()
    }
    
    return {
        searchForm,
        pageForm,
        tableData,
        currentPage,
        total,
        loading,
        queryList,
        resetList,
        search,
        resetSearch,
        handleSizeChange,
        handleCurrentChange,
    }
}
